import logging
from datetime import datetime
from logging.handlers import TimedRotatingFileHandler  # 显式导入
from common.config import Config


class Logger:
    """日志工具类"""

    def __init__(self, name=__name__, when='midnight', interval=1, backup_count=7):
        # 1. 创建日志器对象
        self.logger = logging.getLogger(name)
        self.logger.setLevel(logging.DEBUG)
        # 避免重复添加handler
        if not self.logger.handlers:
            # 2. 设置日志打印级别
            self.logger.setLevel(logging.DEBUG)
            # logging.DEBUG 调试级别
            # logging.INFO 信息级别
            # logging.WARNING 警告级别
            # logging.ERROR 错误级别
            # logging.CRITICAL 严重错误级别

            # 3. 创建处理器对象
            # 控制台对象
            st = logging.StreamHandler()
            st.setLevel(logging.DEBUG)
            # 日志文件对象
            log_dir = Config.BASE_DIR / "logs"
            log_dir.mkdir(exist_ok=True)
            log_file = log_dir / f"test_{datetime.now().strftime('%Y%m%d')}.log"
            fh = logging.handlers.TimedRotatingFileHandler(log_file,
                                                           when=when,
                                                           interval=interval,
                                                           backupCount=backup_count,
                                                           encoding='utf-8')

            # 4. 日志信息格式
            fmt = "%(asctime)s %(levelname)s [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s"
            formatter = logging.Formatter(fmt)

            # 5. 给处理器设置日志信息格式
            st.setFormatter(formatter)
            fh.setFormatter(formatter)

            # 6. 给日志器添加处理器
            self.logger.addHandler(st)
            self.logger.addHandler(fh)

    def get_logger(self):
        return self.logger


# 创建全局日志实例
logger = Logger(__name__).get_logger()
